// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables
import 'dart:async';
import "dart:math";

import 'package:flutter/material.dart';
import 'package:junyeyishu/ui/home/widgets/QGLimitWidget.dart';

import 'package:junyeyishu/widgets/QGWebViewWidget.dart';
import 'package:junyeyishu/widgets/QGWidget.dart';
import 'package:junyeyishu/widgets/QGButton.dart';
import 'package:junyeyishu/utils/utils.dart';
import 'package:junyeyishu/widgets/QGNavigationBar.dart';

class QGSynthesisPage extends StatefulWidget {
  String id;
  QGSynthesisPage({super.key, required this.id});
  @override
  State<QGSynthesisPage> createState() => _QGSynthesisPageState();
}

class _QGSynthesisPageState extends State<QGSynthesisPage> {
  dynamic data;

  String? countdown;
  Timer? timer;

  bool canMerge = false;

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    onRefresh();
  }

  setupCountdown() {
    var endTime = DateTime.parse(data?["event"]?["end_time"] ?? "")
        .millisecondsSinceEpoch;
    var now = getCurrentTime();

    countdown = getCountdown(data?["event"]?["start_time"]);
    if (countdown != null || now < endTime) {
      timer?.cancel();
      timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        var now = getCurrentTime();

        //开始时间 & 结束时间
        try {
          var startTime = DateTime.parse(data?["event"]?["start_time"] ?? "")
              .millisecondsSinceEpoch;
          var endTime = DateTime.parse(data?["event"]?["end_time"] ?? "")
              .millisecondsSinceEpoch;
          canMerge = (now >= startTime) && (now < endTime);
        } catch (e) {}

        countdown = getCountdown(data?["event"]?["start_time"]);
        if (countdown == null && now > endTime) {
          timer.cancel();
        }
        if (mounted) setState(() {});
      });
    }
  }

  onRefresh() {
    var param = {"id": widget.id};
Map<String, dynamic> stringMap = param.cast<String, dynamic>();
    
    Network.post(url_user_combineEventList, data: stringMap).then((res) {
      if (!res.success) {
        toast(res.msg);
        return;
      }

      updateCurrentTime(res.data["timestamp"]);

      data = res.data;

      setupCountdown();
      if (mounted) setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Stack(
          children: [
            SingleChildScrollView(
              child: Stack(
                children: [
                  Column(
                    children: [
                      SizedBox(height: 70.rpx),
                      buildHeader(),
                      SizedBox(height: 20.rpx),
                       buildCondition(),
                      buildTip(),
                    // buildNotice(),
                      SizedBox(height: kSafeBottom + 64.rpx),
                    ],
                  ),
                ],
              ),
            ),
            buildTop(),
            Positioned(bottom: 0, child: buildBottom())
          ],
        ));
  }

  buildTop() {
    return Container(
      color: Colors.transparent,
      child: QGNavigationBar(
        title:"",
        rightItem: GestureDetector(
          onTap: onRecord,
          child: Container(
            padding: EdgeInsets.only(
              top: 6.rpx,
              bottom: 6.rpx,
              left: 10.rpx,
              right: 10.rpx,
            ),
            child: Text(
              '',
              style: TextStyle(
                  color: Color(0xFF111111),
                  fontSize: 11.rpx,
                  fontWeight: FontWeight.normal),
            ),
          ),
        ),
      ),
    );
  }

  buildHeader() {
    return Container(
      width: kScreenWidth,
      padding: EdgeInsets.symmetric(horizontal: 10.rpx),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Stack(
            alignment: Alignment.center,
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(8.rpx),
                  child: AspectRatio(
                    aspectRatio:1,
                    child:QGImage(url:data?["nft"]?["thumb_img"]),
                  ),
                ),
              Positioned(
                bottom: 20.rpx,
                right: 40.rpx,
                left: 40.rpx,
                child: 
                countdown != null
              ? Container(
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(26.rpx),
                      color: Color(0x80000000)),
                  padding:
                      EdgeInsets.symmetric(horizontal: 40.rpx, vertical: 6.rpx),
                  child: RichText(
                      textAlign: TextAlign.center,
                      text: TextSpan(children: [
                        buildText('距离开始时间：', Color(0xFFFFFFFF)),
                        buildText('$countdown', Color(0xFFFFFFFF)),
                      ])),
                )
                : Container(),
              )
            ],
          ),
          
        ],
      ),
    );
  }

  buildText(text, color) {
    return TextSpan(
      text: text,
      style: TextStyle(
          color: color, fontSize: 11.rpx, fontWeight: FontWeight.normal),
    );
  }

  buildCondition() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10.rpx),
      child: Column(
        children: [
          buildConditionTitle(),
          SizedBox(height: 20.rpx),
       
          buildConditionItems(),
        ],
      ),
    );
  }

  buildConditionTitle() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 30.rpx),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          SizedBox(width: 7.rpx),
          Expanded(
            child: Column(
              children: [
                Text(
                  data?["nft"]?["name"] ?? "",
                  style: TextStyle(
                      color: Color(0xFFFFFFFF),
                      fontSize: 20.rpx,
                      fontWeight: FontWeight.bold),
                ),
                SizedBox(height: 4.rpx),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text("限量 ",style: TextStyle(fontSize: 13,color: Color(0XFF989EA4))),
                    Text(data?["event"]?["max_num"] ?? "",style: TextStyle(fontSize: 13,color: Color(0XFF989EA4))),
                    Text("份 ",style: TextStyle(fontSize: 13,color: Color(0XFF989EA4))),
                  ]
                )
              ],
            ),
          ),
          SizedBox(width: 7.rpx),
        ],
      ),
    );
  }

  buildArrow() {
    return Align(
      alignment: Alignment.center,
      child: QGImage(asset: "synthesis_detail_arrow", width: 29.rpx),
    );
  }

  buildTip() {
    return Container(
      alignment: Alignment.center,
      child: Text(
        "集齐以上数字资产即可进行合成",
        style: TextStyle(
            fontWeight: FontWeight.normal,
            fontSize: 12.rpx,
            color: Color(0xFF0A071A)),
      ),
    );
  }

  buildConditionItems() {
    List<Widget> children = [];

    for (var item in data?["formulas"] ?? []) {
      children.add(buildConditionCell(item));
    }

    return Container(
      decoration: BoxDecoration(
        color: Color(0XFF232A32),
        borderRadius: BorderRadius.circular(10.rpx)
      ),
      alignment: Alignment.center,
      padding: EdgeInsets.only(bottom: 10.rpx),
      child: Column(
        children: [
          SizedBox(height: 15.rpx,),
          Text("合成条件 ",style: TextStyle(fontSize: 18.rpx,color: Color(0XFFFFFFFF))),
          SizedBox(height: 3.rpx,),
          Text("集齐一下藏品即可兑换",style: TextStyle(fontSize: 13.rpx,color: Color(0XFF989EA4))),
          SizedBox(height: 20.rpx,),

           Wrap(
            spacing: 10.rpx,
            runSpacing: 10.rpx,
            children: children,
          ),
        ],
      )
     
    );
  }

  buildConditionCell(itemData) {
    var ownNum = int.parse(itemData["goods_num_mine"]);
    var needNum = int.parse(itemData["goods_num"]);

    return Column(
      children: [
        Container(
            decoration: BoxDecoration(
              color: Color(0XFF0C1012),
              borderRadius: BorderRadius.only(bottomLeft: Radius.circular(5.rpx),bottomRight: Radius.circular(5.rpx),),
            ),
          child: Column(
            children: [
                    QGImage(
                    url: itemData["thumb_img"],
                    width: 155.rpx,
                    height: 155.rpx),
                    SizedBox(height: 10.rpx),
                    Text(
                  itemData["name"] ?? "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Color(0xFFffffff),
                      fontSize: 14.rpx,
                      fontWeight: FontWeight.bold),
                ),
                SizedBox(height: 3.rpx),
                    Text(
                        '${itemData["goods_num_mine"]}/${itemData["goods_num"]}',
                        style: TextStyle(
                            color: Color(0xFF989EA4),
                            fontSize: 12.rpx,
                            fontWeight: FontWeight.bold),
                      ),
                      SizedBox(height: 10.rpx),

              // Stack(
              //   children: [
              //   QGImage(
              //       url: itemData["thumb_img"],
              //       width: 150.rpx,
              //       height: 150.rpx),
              //     // ownNum < needNum
              //     //     ? Container(
              //     //         width: 75.rpx,
              //     //         height: 75.rpx,
              //     //         margin: EdgeInsets.only(top: 8.rpx, right: 8.rpx),
              //     //         decoration: BoxDecoration(
              //     //             borderRadius: BorderRadius.circular(4.rpx),
              //     //             color: const Color.fromRGBO(17, 17, 17, 0.5)),
              //     //       )
              //     //     : Container(width: 0.rpx),
              //     // ownNum < needNum
              //     //     ? Container(
              //     //         width: 75.rpx,
              //     //         height: 75.rpx,
              //     //         margin: EdgeInsets.only(top: 8.rpx, right: 8.rpx),
              //     //         alignment: Alignment.center,
              //     //         child: QGImage(
              //     //             asset: "synthesis_detail_lock", width: 13.rpx),
              //     //       )
              //     //     : Container(width: 0.rpx),
              //     Positioned(
              //       top: 0.rpx,
              //       right: 0.rpx,
              //       child: Container(
              //         alignment: Alignment.center,
              //         padding: EdgeInsets.symmetric(
              //             horizontal: 6.rpx, vertical: 3.rpx),
              //         decoration: BoxDecoration(
              //           borderRadius: BorderRadius.circular(10.rpx),
              //           color: Color(0xFFDEFF80),
              //         ),
              //         child: Text(
              //           '${itemData["goods_num_mine"]}/${itemData["goods_num"]}',
              //           style: TextStyle(
              //               color: Color(0xFF111111),
              //               fontSize: 12.rpx,
              //               fontWeight: FontWeight.bold),
              //         ),
              //       ),
              //     )
              //   ],
              // ),
              // SizedBox(height: 10.rpx),
              // Container(
              //   alignment: Alignment.center,
              //   width: 75.rpx,
              //   child: Text(
              //     itemData["name"] ?? "",
              //     maxLines: 1,
              //     overflow: TextOverflow.ellipsis,
              //     style: TextStyle(
              //         color: Color(0xFFffffff),
              //         fontSize: 14.rpx,
              //         fontWeight: FontWeight.bold),
              //   ),
              // ),
            ],
          ),
        ),
      ],
    );
  }

  buildNotice() {
    return Container(
      margin: EdgeInsets.only(top: 10.rpx, left: 10.rpx, right: 10.rpx),
      padding: EdgeInsets.symmetric(horizontal: 10.rpx, vertical: 10.rpx),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.rpx),
        color: Color(0xFFF8F8F6),
      ),
      child: Column(children: [
        Text(
          '合成须知',
          style: TextStyle(
              color: Color(0xFF111111),
              fontSize: 16.rpx,
              fontWeight: FontWeight.bold),
        ),
        QGWebViewWidget(
            str: data?["event"]?["content"],
            bgColor: "#F8F8F6",
            textColor: "#111111")
      ]),
    );
  }

  buildBottom() {
    return Container(
      padding: EdgeInsets.only(
          left: 20.rpx,
          right: 20.rpx,
          top: 10.rpx,
          bottom: max(10, kSafeBottom)),
      width: kScreenWidth,
      decoration: BoxDecoration(color: Color(0xFF232A32)),
      child: QGButton(
        title: "立即合成",
        enable: data?["canMerge"] != 0 && canMerge,
        onTap: onCompose,
      ),
    );
  }

  onRecord() {
    Navigator.of(context).pushNamed(PageSynthesisRecord, arguments: widget.id);
  }

  onCompose() {
    var param = {"id": widget.id};
Map<String, dynamic> stringMap = param.cast<String, dynamic>();

    Network.post(url_user_combineNft, data: stringMap, context: context)
        .then((res) {
      if (!res.success) {
        toast(res.msg);
        return;
      }
      toast(res.data["message"] ?? "");
      onRefresh();
    });
  }
}
